package 三种实现方式;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyCallable implements Callable<Integer> {
    private int count;

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            count += i;
            Thread.sleep(500);
        }
        return count; // 返回计算结果
    }
}

public class CallableExample {
    public static void main(String[] args) {
        MyCallable callable = new MyCallable();

        // 用FutureTask包装Callable
        FutureTask<Integer> futureTask = new FutureTask<>(callable);

        // FutureTask实现了RunnableFuture，而RunnableFuture继承了Runnable
        Thread thread = new Thread(futureTask, "CallableThread");
        thread.start();

        try {
            // do something else in main thread...

            // 获取子线程的返回值，会阻塞主线程直到计算完成
            Integer result = futureTask.get();
            System.out.println("Final count is: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
